package assignment.ton.gui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.regex.PatternSyntaxException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import assignment.ton.def.Class;
/**
 * Frame called when the variables button is clicked
 * @author Tim
 *
 */
public class VariableFrame extends JFrame implements ActionListener{
	private static final long serialVersionUID = -2473783470890451711L;
	private Class theClass;
	private MainFrame mainFrame;
	private JComboBox variableList;
	private JButton add, delete;
	public VariableFrame(Class cl, MainFrame f){
		theClass = cl;
		mainFrame = f;
		this.setTitle("Variables");
		this.addWindowListener(new WindowAdapter(){ //now make it do something more interesting
			public void windowClosing(WindowEvent e){
				quit();
			}
		});
		this.setLayout(new GridBagLayout());
		this.setIconImage(new ImageIcon(getClass().getResource("ton_icon.gif")).getImage());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(2,2,2,2);
		this.setResizable(false);
		this.setLocationRelativeTo(mainFrame);
		String [] data = theClass.getVariableList();
		variableList = new JComboBox(data);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 1;
		this.add(variableList, c);
		add = new JButton("Add");
		c.gridx = 1;
		this.add(add, c);
		add.addActionListener(this);
		delete = new JButton("Delete");
		c.gridx = 2;
		this.add(delete, c);
		delete.addActionListener(this);
		pack();
	}
	public void quit(){
		mainFrame.setAction(mainFrame.getPreviousAction());
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();
		if("Add".equals(actionCommand)){
			AddVariable v = new AddVariable(mainFrame.getSelected(),this,mainFrame);
			v.setVisible(true);
		}else if("Delete".equals(actionCommand)){
			try{
				String theVar = (String)variableList.getSelectedItem();
				String[] varArray = theVar.split(":");
				theVar = varArray[0];
				theClass.removeVariable(theVar);
				rebuildList();
			}catch(PatternSyntaxException f){
				String eT = "Error!";
				String error = "Quit trying to delete nothing";
				JOptionPane.showMessageDialog(this, error, eT, JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	/**
	 * This method removed all items from the list and rebuilds it
	 */
	public void rebuildList(){
		variableList.removeAllItems();
		String [] data = theClass.getVariableList();
		for(int i = 0; i<data.length; i++){
			variableList.addItem(data[i]);
		}
		pack();
	}
}
